'use client';

import { useEffect, useRef, useState } from 'react';

interface VideoPlayerProps {
  url: string;
  title?: string;
  isLoading?: boolean;
  hasError?: boolean;
  hasTimeout?: boolean;
  onLoad?: () => void;
  onError?: () => void;
  onOpenInNewTab?: () => void;
}

export default function VideoPlayer({
  url,
  title,
  isLoading = true,
  hasError = false,
  hasTimeout = false,
  onLoad,
  onError,
  onOpenInNewTab,
}: VideoPlayerProps) {
  const [playerType, setPlayerType] = useState<'iframe' | 'video'>('iframe');
  const [retryCount, setRetryCount] = useState(0);
  const iframeRef = useRef<HTMLIFrameElement>(null);
  
  // 尝试通过直接解析视频源的方式加载
  const tryDirectPlay = async () => {
    // 这里模拟一个尝试直接解析视频源的过程
    // 实际项目中可能需要调用特定的API或库来解析视频源
    console.log('尝试直接解析视频源...');
    // 返回 false 表示解析失败，仍然使用iframe方式
    return false;
  };
  
  // 当URL变化时重置播放器
  useEffect(() => {
    if (!url) return;
    
    const init = async () => {
      // 尝试直接播放
      const canDirectPlay = await tryDirectPlay();
      setPlayerType(canDirectPlay ? 'video' : 'iframe');
    };
    
    init();
    setRetryCount(0);
  }, [url]);
  
  // 处理加载错误
  const handleError = () => {
    if (onError) onError();
    // 如果是iframe方式加载失败，可以尝试其他方式
    if (playerType === 'iframe' && retryCount < 1) {
      setRetryCount(prev => prev + 1);
      // 可以尝试切换到video方式
      // setPlayerType('video');
    }
  };
  
  // 处理加载完成
  const handleLoad = () => {
    if (onLoad) onLoad();
  };
  
  // 在新标签页打开
  const openInNewTab = () => {
    if (onOpenInNewTab) {
      onOpenInNewTab();
    } else if (url) {
      // 添加备用方案，直接在组件内处理新标签页打开
      window.open(url, '_blank');
    }
  };
  
  return (
    <div className="pt-[56.25%] w-full bg-gray-800 rounded-lg overflow-hidden relative">
      {isLoading && (
        <div className="absolute inset-0 flex items-center justify-center bg-gray-800">
          <div className="flex flex-col items-center">
            <svg className="animate-spin h-8 w-8 text-white mb-2" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
              <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
              <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
            </svg>
            <span className="text-white text-sm">加载中...</span>
            <p className="text-gray-300 text-xs mt-2 max-w-xs text-center">正在加载解析后的视频，可能需要几秒钟...</p>
          </div>
        </div>
      )}
      
      {hasTimeout && !hasError && (
        <div className="absolute inset-0 flex items-center justify-center bg-gray-800">
          <div className="flex flex-col items-center p-4 text-center">
            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-10 h-10 text-yellow-500 mb-2">
              <path strokeLinecap="round" strokeLinejoin="round" d="M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            <p className="text-white font-medium mb-2">加载超时</p>
            <p className="text-gray-300 text-sm mb-3">当前解析接口响应较慢或视频可能不支持内嵌播放</p>
            <div className="flex gap-2">
              <button 
                onClick={openInNewTab}
                className="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 transition-colors flex items-center"
              >
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-4 h-4 mr-1">
                  <path strokeLinecap="round" strokeLinejoin="round" d="M13.5 6H5.25A2.25 2.25 0 003 8.25v10.5A2.25 2.25 0 005.25 21h10.5A2.25 2.25 0 0018 18.75V10.5m-10.5 6L21 3m0 0h-5.25M21 3v5.25" />
                </svg>
                在新标签页打开
              </button>
              {retryCount < 2 && (
                <button 
                  onClick={() => {
                    console.log("重试加载按钮被点击");
                    try {
                      // 重置加载状态
                      if (onLoad) onLoad();
                      // 增加重试计数
                      setRetryCount(prev => prev + 1);
                      // 使用setTimeout确保DOM更新后再设置src
                      setTimeout(() => {
                        if (iframeRef.current) {
                          iframeRef.current.src = url;
                        }
                      }, 100);
                    } catch (err) {
                      console.error("重试加载错误:", err);
                    }
                  }}
                  className="px-4 py-2 bg-gray-700 text-white rounded-md hover:bg-gray-600 transition-colors flex items-center"
                >
                  <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-4 h-4 mr-1">
                    <path strokeLinecap="round" strokeLinejoin="round" d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0l3.181 3.183a8.25 8.25 0 0013.803-3.7M15.485 4.355a8.25 8.25 0 00-13.803 3.7m0 0l-3.181-3.183m13.803 3.183 3.181 3.182" />
                  </svg>
                  重试加载
                </button>
              )}
            </div>
          </div>
        </div>
      )}
      
      {hasError && (
        <div className="absolute inset-0 flex items-center justify-center bg-gray-800">
          <div className="flex flex-col items-center p-4 text-center">
            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-10 h-10 text-red-500 mb-2">
              <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v3.75m9-.75a9 9 0 11-18 0 9 9 0 0118 0zm-9 3.75h.008v.008H12v-.008z" />
            </svg>
            <p className="text-white font-medium mb-2">播放器加载失败</p>
            <p className="text-gray-300 text-sm mb-3">当前视频可能不支持内嵌播放或解析接口无法正常工作</p>
            <div className="flex gap-2">
              <button 
                onClick={openInNewTab}
                className="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 transition-colors flex items-center"
              >
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-4 h-4 mr-1">
                  <path strokeLinecap="round" strokeLinejoin="round" d="M13.5 6H5.25A2.25 2.25 0 003 8.25v10.5A2.25 2.25 0 005.25 21h10.5A2.25 2.25 0 0018 18.75V10.5m-10.5 6L21 3m0 0h-5.25M21 3v5.25" />
                </svg>
                在新标签页打开
              </button>
              {retryCount < 2 && (
                <button 
                  onClick={() => {
                    console.log("重试加载按钮被点击");
                    try {
                      // 重置加载状态
                      if (onLoad) onLoad();
                      // 增加重试计数
                      setRetryCount(prev => prev + 1);
                      // 使用setTimeout确保DOM更新后再设置src
                      setTimeout(() => {
                        if (iframeRef.current) {
                          iframeRef.current.src = url;
                        }
                      }, 100);
                    } catch (err) {
                      console.error("重试加载错误:", err);
                    }
                  }}
                  className="px-4 py-2 bg-gray-700 text-white rounded-md hover:bg-gray-600 transition-colors flex items-center"
                >
                  <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-4 h-4 mr-1">
                    <path strokeLinecap="round" strokeLinejoin="round" d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0l3.181 3.183a8.25 8.25 0 0013.803-3.7M15.485 4.355a8.25 8.25 0 00-13.803 3.7m0 0l-3.181-3.183m13.803 3.183 3.181 3.182" />
                  </svg>
                  重试加载
                </button>
              )}
            </div>
          </div>
        </div>
      )}
      
      {playerType === 'iframe' && (
        <iframe
          ref={iframeRef}
          key={`${url}-${retryCount}`} // 添加重试计数作为key以便重新渲染
          src={url}
          className="absolute top-0 left-0 w-full h-full border-0"
          allowFullScreen
          allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
          title={title || "视频播放器"}
          onLoad={handleLoad}
          onError={handleError}
          sandbox="allow-same-origin allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox allow-presentation allow-top-navigation"
          referrerPolicy="no-referrer"
          loading="eager"
          style={{zIndex: 10}} // 增加z-index确保iframe在正确的层级
        ></iframe>
      )}
      
      {playerType === 'video' && (
        <video
          controls
          autoPlay
          className="absolute top-0 left-0 w-full h-full"
          onLoadedData={handleLoad}
          onError={handleError}
        >
          <source src={url} />
          您的浏览器不支持视频播放，请尝试使用其他浏览器。
        </video>
      )}
      
      {/* 隐藏的链接预连接 */}
      <div style={{ display: 'none' }}>
        <link rel="preconnect" href={new URL(url).origin} />
        <link rel="prerender" href={url} />
      </div>
    </div>
  );
} 